﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Text;

/*
我用C#做的WebService中有几个WebMethod需要使用out和ref参数，但是在WebService   Behavior中不知道怎么调用这样的WebMethod。   
其实很简单，在调用的入口处，ref与普通参数一样写，out参数不用写。在返回值时，用result.value["参数名"]来去参数，用result.value[WebMethod的名字   +   "Result"]来取返回值结果。
*/
public partial class flt_avail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            lblError.Text = "";
            if (IsRobot.Test("Query", 1, 60, 6))
            {
                lblError.Text = "Please don't query continually!";
                return;
            }
            return;
        }
        StringBuilder sFlights = new StringBuilder();
        int trip_count,i,adt,chd,inf;

        if (Session["TRIP_COUNT"] == null)
        {
            btnNext.Enabled = false;
            lblError.Text = "非法页面调用!";
            return;
        }
        trip_count = Convert.ToInt16(Session["TRIP_COUNT"].ToString());


        adt = Convert.ToInt16(Session["ADT_COUNT"].ToString());
        chd = Convert.ToInt16(Session["CHD_COUNT"].ToString());
        inf = Convert.ToInt16(Session["INF_COUNT"].ToString());
        if (adt < 0 || chd < 0 || inf < 0 || (adt < inf) || adt + chd > 50)
        {
            lblError.Text = "乘客人数过多!";
            btnNext.Enabled = false;
            return;
        }


        string[] ori/*trips*/ = new string[trip_count + 1];
        string[] des = new string[trip_count + 1];
        string[] trip_dates = new string[trip_count];
        string fare_key;
        for (i = 1; i <= trip_count; i++)
        {
            ori/*trips*/[i - 1] = Session["lstOriCity" + i.ToString()].ToString();
            des[i - 1] = Session["lstDesCity" + i.ToString()].ToString();
            trip_dates[i - 1] = Session["txtFltDate" + i.ToString()].ToString();
        }
        //trips[i-1] = Session["lstCity" + i.ToString()].ToString();

        CRSI.Query instFlt = new CRSI.Query();
        //用session认证用户方案失败了！可能WSE可行
        //System.Net.CookieContainer cookieJar = new System.Net.CookieContainer();
        //instFlt.CookieContainer=cookieJar;
        DataSet dsFlgiths;
        int ret_code;
        string ret_msg;
        string lastAirline, lastFlt;
        //string lastCabin, lastClass;
        //string pwd_sha1 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Application["PWD"].ToString(), "SHA1");
        string sign;

        sFlights.Append("<table>");
        try
        {
            for (i = 1; i <= trip_count; i++)
            {
                sFlights.Append("<tr style=\"background-color: mediumseagreen;\"><th>&lt;" + i.ToString() + "&gt;</th><th>" + trip_dates[i - 1] + " </th><th colspan='2'>航班号</th><th>机型</th><th colspan='100'>可用票价</th></tr>");
                sign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(ori[i - 1] + "|" + des[i - 1] + "|" + Convert.ToDateTime(trip_dates[i - 1]).ToString("yyyyMMdd") + "|" + Application["HASH_PWD"].ToString(), "MD5");
                dsFlgiths = instFlt.QueryFlights(ori[i - 1], des[i - 1], 2, Convert.ToDateTime(trip_dates[i - 1]), Convert.ToInt16(adt + chd), Convert.ToInt16(i), Convert.ToInt16(trip_count), Application["UID"].ToString(), sign, out ret_code, out ret_msg);
                if (ret_code != 0)
                {
                    if (ret_code == -1)
                    {
                        lblError.Text = ret_msg;
                    }
                    //else if (ret_code == -10)//login first
                    //{
                    //    lblError.Text = "login first";
                    //    CRSI.Session inst = new CRSI.Session();
                    //    inst.CookieContainer = cookieJar;
                    //    ret_code = inst.Login(Application["UID"].ToString(), Application["PWD"].ToString());

                    //}
                    else if (ret_code == 1)
                    {
                        lblError.Text = "Log on failed!";
                    }
                    else if (ret_code == 2)
                    {
                        lblError.Text = "Daylight saving time error!";
                    }
                    else
                        lblError.Text = "Unknow error! Step " + i.ToString() + ":" + ret_code.ToString();
                    return;
                }

                lastAirline = ""; lastFlt = "";
                //lastCabin = "";lastClass = "";

                foreach (DataRow row_flights in dsFlgiths.Tables[0].Rows)
                {
                    if (lastAirline != row_flights["airline"].ToString() || lastFlt != row_flights["flt_no"].ToString())
                    {//it may be first flight also
                        if(lastAirline != "")
                        {//not for first flight
                            sFlights.Append("</tr>");
                        }
                        sFlights.Append("<tr><td></td><td align='left'>"+Convert.ToDateTime(row_flights["dep_time"]).ToShortTimeString()+" "+row_flights["ori_apt_name"]+"<br/>"+Convert.ToDateTime(row_flights["arr_time"]).ToShortTimeString()+" "+row_flights["des_apt_name"]
                            +"</td><td>"+row_flights["airline"].ToString() + row_flights["flt_no"].ToString()+"</td><td>");
                            
                        if (row_flights["direct_fly"].ToString() == "0")
                            sFlights.Append("经停</td><td>");
                        else
                            sFlights.Append("直达</td><td>");
                        sFlights.Append(row_flights["ac_type"].ToString() + "</td>");

                        lastAirline = row_flights["airline"].ToString();
                        lastFlt = row_flights["flt_no"].ToString();
                        //lastCabin = "";
                    }

                    fare_key = "AIRLINE=" + row_flights["airline"].ToString() + "&FARE_CODE=" + row_flights["fare_code"] + "&DBF=" + row_flights["dbf"].ToString() + "&ORI=" + ori[i - 1] + "&DES=" + des[i - 1] + "&TAX_TYPE=" + row_flights["tax_type"].ToString() + "&SEG_SN=" + row_flights["seg_sn"].ToString() + "&LANG=2";

                    //tabCell.Text = "<input type=\"radio\" name=\"KEY" + i.ToString() + "\" value=\"" + row_flights["flt_date"].ToString() + "|" + row_flights["airline"] + "|" + row_flights["flt_no"] + "|" + trips[i - 1] + "|" + trips[i] + "|" + row_cabins["cabin"] + "|" + foundRows[j]["class"] + "|" + foundFares[k]["code"] + "|" + row_flights["international"].ToString() + "|" + row_flights["dep_time"].ToString() + "|" + row_flights["arr_time"].ToString() + "\" onclick=\"AjaxRequest('fare_details.aspx?" + fare_key + "')\">";
                    //改为传入机场代码而非城市代码！
                    sFlights.Append("<td><input type=\"radio\" name=\"KEY" + i.ToString() + "\" value=\"" + row_flights["flt_date"].ToString() + "|" + row_flights["airline"] + "|" + row_flights["flt_no"] + "|" + row_flights["ori_airport"] + "|" + row_flights["des_airport"] + "|" + row_flights["cabin"] + "|" + row_flights["class"] + "|" + row_flights["fare_code"] + "|" + row_flights["international"].ToString() + "|" + row_flights["dep_time"].ToString() + "|" + row_flights["arr_time"].ToString() + "|" + row_flights["dbf"].ToString() + "|" + row_flights["seg_sn"].ToString() + "\" onclick=\"AjaxRequest('fare_details.aspx?" + fare_key + "')\">");

                    sFlights.Append("<a href='fare_details.aspx?" + fare_key + "'>" + row_flights["fare_name"].ToString().Trim() + "</a>" + /*"(" + row_flights["seg_sn"].ToString() + "/" + row_flights["seg_total"].ToString() + ")" + "/"  +*/ row_flights["currency"].ToString() + Convert.ToSingle(row_flights["adt_price"]).ToString() + /*"/" + Convert.ToSingle(row_flights["chd_price"]).ToString() + "/" + Convert.ToSingle(row_flights["inf_price"]).ToString() +*/ "</td>");

                }
                if (dsFlgiths.Tables[0].Rows.Count == 0)
                    btnNext.Enabled = false;
                sFlights.Append("</tr>");
                dsFlgiths.Clear();

            }
            sFlights.Append("</table>");
            litFlights.Text = sFlights.ToString();

        }
        catch (Exception ex)
        {
            lblError.Text = ex.Message;
            btnNext.Enabled = false;
        }

    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        //int trip_count,i;
        //string sTmp;
        //DateTime DepTime, ArrTime, LastArrTime;
        //TimeSpan span;// = new TimeSpan(0, 0, 0);
        //int link_time;
        //for (int i = 1; i <= trip_count; i++)
        //{
        //    sTmp = Request.Form["KEY" + i.ToString()];
        //    if (sTmp == null)
        //    {
        //        lblError.Text = "Please select your desired fare for each trip segment.";
        //        butNext.Enabled = false;
        //        return;
        //    }
        //    //check link time....
        //    sSplited = sTmp.Split('|');

        //    Session["FLT_DATE" + i.ToString()] = sSplited[0];
        //    Session["FLT_NO" + i.ToString()] = sSplited[2];
        //    Session["AIRLINE" + i.ToString()] = sSplited[1];
        //    Session["ORI" + i.ToString()] = sSplited[3];//airport!not city!
        //    Session["DES" + i.ToString()] = sSplited[4];
        //    Session["CABIN" + i.ToString()] = sSplited[5];
        //    Session["CLASS" + i.ToString()] = sSplited[6];
        //    Session["FARE" + i.ToString()] = sSplited[7];

        //    DepTime = Convert.ToDateTime(sSplited[9]);
        //    ArrTime = Convert.ToDateTime(sSplited[10]);
        //    //if (sSplited[8] == "1")//domestic = true;
        //    //{
        //    //    link_time = Convert.ToInt16(sSplited[11]);
        //    //}
        //    //else
        //    //{
        //    //    link_time =  Convert.ToInt16(sSplited[12]);
        //    //}
        //    link_time = 30;//前置检查至少要求提前半小时衔接？=系统最低衔接时间
        //    span = new TimeSpan(0, link_time, 0);
        //    if (i > 1)//need to check link time
        //    {
        //        if (DepTime - LastArrTime < span)
        //        {
        //            lblError.Text = sSplited[3] + "-" + sSplited[4] + "衔接时间不够，请更换航班！";
        //            butNext.Enabled = false;
        //            break;
        //        }
        //    }
        //    LastArrTime = ArrTime;
        //}
        //Response.Redirect("order_contact.aspx");
    }



}
